package cn.simon.controller;

import cn.hutool.crypto.SecureUtil;
import cn.simon.model.BiliUser;
import cn.simon.service.Impl.LoginServiceImpl;
import cn.simon.util.Site;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.java.Log;

import java.io.IOException;

@Log
@WebServlet(value = "/register")
public class Bili_RegisterController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(Site.PREFIX + "/bilibili_register"+Site.SUFFIX).forward(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username  = req.getParameter("username");
        String password = req.getParameter("password");
        String verify = req.getParameter("verify");
        HttpSession session  = req.getSession();

        String code = (String) session.getAttribute("code");
        log.info(code+"--------------"+verify);
        if(!code.equals(verify)){
            session.setAttribute("megRegister","验证码不正确");
            resp.sendRedirect(req.getContextPath() + "/register");
           // req.getRequestDispatcher(Site.PREFIX + "/bilibili_register" + Site.SUFFIX).forward(req,resp);
            return;
        }

        System.out.println(username + "------------"+password);

        LoginServiceImpl loginService = new LoginServiceImpl();
        BiliUser user = loginService.getPaword(username);

        if(user != null){
            req.setAttribute("megRegister","该用户名已被注册");
            req.getRequestDispatcher(Site.PREFIX + "/bilibili_register"+Site.SUFFIX).forward(req,resp);
            return;
        }
        session.setAttribute("megRegister",null);
        password = SecureUtil.md5(password).toLowerCase();
        BiliUser biliUser = BiliUser.builder()
                .biliuserName(username)
                .biliuserPassword(password)
                .build();
        loginService.addBiliUser(biliUser);
//        req.setAttribute("meg","注册成功");
//         req.getRequestDispatcher(Site.PREFIX+"/registerSuccess"+Site.SUFFIX);
       resp.sendRedirect(req.getContextPath() + "/success");
    }
}
